package de.szut.tictactoe.game;

public class Field {
	private FieldGroup[] horizontalGroups;
	private FieldGroup[] verticalGroups;
	private FieldGroup[] diagonalGroups;
	
	public Field() {
		// generates the field
		int fieldSize = 3;
		horizontalGroups = new FieldGroup[fieldSize];
		verticalGroups = new FieldGroup[fieldSize];
		diagonalGroups = new FieldGroup[2];
		
		for (int generationIndex = 0; generationIndex != fieldSize; generationIndex ++) {
			horizontalGroups[generationIndex] = new FieldGroup();
			verticalGroups[generationIndex] = new FieldGroup();
		}
		diagonalGroups[0] = new FieldGroup();
		diagonalGroups[1] = new FieldGroup();
		
		for (int horizontalIndex = 0; horizontalIndex != fieldSize; horizontalIndex ++) {
			for (int verticalIndex = 0; verticalIndex != fieldSize; verticalIndex ++) {
				Box currentBox = new Box();
				horizontalGroups[horizontalIndex].addBox(currentBox);
				verticalGroups[verticalIndex].addBox(currentBox);
				
				if (horizontalIndex == 0 && verticalIndex == 0 || horizontalIndex == 2 && verticalIndex == 2) {
					diagonalGroups[0].addBox(currentBox);
				} else if (horizontalIndex == 0 && verticalIndex == 2 || horizontalIndex == 2 && verticalIndex == 0) {
					diagonalGroups[1].addBox(currentBox);
				} else if (horizontalIndex == 1 && verticalIndex == 1) {
					diagonalGroups[0].addBox(currentBox);
					diagonalGroups[1].addBox(currentBox);
				}
			}
		}
	}
	
	public boolean gameHasEnded() {
		for (FieldGroup currentGroup : horizontalGroups) {
			if (currentGroup.containsBoxThrice()) {
				return true;
			}
		}
		
		for (FieldGroup currentGroup : verticalGroups) {
			if (currentGroup.containsBoxThrice()) {
				return true;
			}
		}
		
		for (FieldGroup currentGroup : diagonalGroups) {
			if (currentGroup.containsBoxThrice()) {
				return true;
			}
		}
		return false;
	}
	
	public void setValue(boolean value, int x, int y) {
		verticalGroups[x].getBoxes().get(y).setState(value);
	}
}
